/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package battle.ship.uinterface;

import battle.ship.controller.Client;
import battle.ship.controller.Server;
import battle.ship.model.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Carlos
 */
public class UserInterface extends javax.swing.JFrame {

    /**
     * Creates new form UserInterface
     */
    
    private final JButton Mybt[][] = new BattleShipJButton[10][10];
    private final JButton Yourbt[][] = new BattleShipJButton[10][10];
    private Game game = new Game(2);
    private final ButtonGroup jrbGroup = new ButtonGroup();
    private final ButtonGroup jrbGTypeServer = new ButtonGroup();
    private final Player IP = new HumanPlayer(" ");
    
    public UserInterface() {
        
        initComponents();
        jpMy.setVisible(false);
        jpYour.setVisible(false);
        this.paintBoard(jpYour,Yourbt,false);
        this.paintBoard(jpMy,Mybt,true);
        
        
        jpMy.setVisible(true);
        jpYour.setVisible(true);
        

        this.game.addPalyer(IP);
        jrbGTypeServer.add(jRServidor);
        jrbGTypeServer.add(jRCliente);
        jrbGroup.add(jRPortavioes);
        jrbGroup.add(jRsubmarino);
        jrbGroup.add(jRBarco3canos);
        jrbGroup.add(jRBarci2canos);
        jrbGroup.add(jRBarco1cano);
        /*
        statusPanel = new JPanel();
        statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
        this.add(statusPanel, BorderLayout.SOUTH);
        statusPanel.setPreferredSize(new Dimension(this.getWidth(), 16));
        statusPanel.setLocation(30, 30);
        statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
        statusLabel = new JLabel("status");
        statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
        statusPanel.add(statusLabel);

        statusPanel.setVisible(true);
        */
      
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popupMenu1 = new java.awt.PopupMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
        jpMy = new javax.swing.JPanel();
        jladdNomePlayer = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPbarcos = new javax.swing.JPanel();
        jRsubmarino = new javax.swing.JRadioButton();
        jRPortavioes = new javax.swing.JRadioButton();
        jRBarco3canos = new javax.swing.JRadioButton();
        jRBarci2canos = new javax.swing.JRadioButton();
        jRBarco1cano = new javax.swing.JRadioButton();
        jPPlayer = new javax.swing.JPanel();
        jBOk = new javax.swing.JButton();
        jTnome = new javax.swing.JTextField();
        jpYour = new javax.swing.JPanel();
        jPligaçao = new javax.swing.JPanel();
        jRCliente = new javax.swing.JRadioButton();
        jRServidor = new javax.swing.JRadioButton();
        jTIP = new javax.swing.JTextField();
        jBLigar = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        JMContinuarJogo = new javax.swing.JMenuItem();
        jMGuardar = new javax.swing.JMenuItem();
        jMSair = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        popupMenu1.setLabel("popupMenu1");

        jMenuItem5.setText("jMenuItem5");

        jRadioButtonMenuItem1.setSelected(true);
        jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setForeground(new java.awt.Color(0, 0, 0));

        jpMy.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(51, 51, 51)));
        jpMy.setEnabled(false);
        jpMy.setMaximumSize(new java.awt.Dimension(300, 300));
        jpMy.setMinimumSize(new java.awt.Dimension(300, 300));
        jpMy.setPreferredSize(new java.awt.Dimension(300, 300));

        javax.swing.GroupLayout jpMyLayout = new javax.swing.GroupLayout(jpMy);
        jpMy.setLayout(jpMyLayout);
        jpMyLayout.setHorizontalGroup(
            jpMyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 298, Short.MAX_VALUE)
        );
        jpMyLayout.setVerticalGroup(
            jpMyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 298, Short.MAX_VALUE)
        );

        jladdNomePlayer.setText("Human Player");

        jLabel1.setText("Estado da ligação: ");

        jLabel2.setText("ON");

        jPbarcos.setBorder(javax.swing.BorderFactory.createTitledBorder("Barcos"));
        jPbarcos.setEnabled(false);

        jRsubmarino.setText("Submarinos");

        jRPortavioes.setText("Porta-Aviões");

        jRBarco3canos.setText("Barco de 3 Canos");

        jRBarci2canos.setText("Barco de 2 Canos");

        jRBarco1cano.setText("Barco de 1 Canos");

        javax.swing.GroupLayout jPbarcosLayout = new javax.swing.GroupLayout(jPbarcos);
        jPbarcos.setLayout(jPbarcosLayout);
        jPbarcosLayout.setHorizontalGroup(
            jPbarcosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPbarcosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPbarcosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRBarci2canos)
                    .addComponent(jRsubmarino)
                    .addComponent(jRPortavioes)
                    .addComponent(jRBarco1cano))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPbarcosLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jRBarco3canos)
                .addContainerGap())
        );
        jPbarcosLayout.setVerticalGroup(
            jPbarcosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPbarcosLayout.createSequentialGroup()
                .addComponent(jRsubmarino)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRPortavioes)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRBarco3canos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRBarci2canos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRBarco1cano)
                .addContainerGap(10, Short.MAX_VALUE))
        );

        jPPlayer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jBOk.setText("Ok");
        jBOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBOkActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPPlayerLayout = new javax.swing.GroupLayout(jPPlayer);
        jPPlayer.setLayout(jPPlayerLayout);
        jPPlayerLayout.setHorizontalGroup(
            jPPlayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPPlayerLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTnome, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jBOk, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(66, 66, 66))
        );
        jPPlayerLayout.setVerticalGroup(
            jPPlayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPPlayerLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPPlayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTnome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBOk))
                .addGap(72, 72, 72))
        );

        jpYour.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(51, 51, 51)));
        jpYour.setEnabled(false);
        jpYour.setMaximumSize(new java.awt.Dimension(300, 300));
        jpYour.setMinimumSize(new java.awt.Dimension(300, 300));
        jpYour.setPreferredSize(new java.awt.Dimension(300, 300));

        javax.swing.GroupLayout jpYourLayout = new javax.swing.GroupLayout(jpYour);
        jpYour.setLayout(jpYourLayout);
        jpYourLayout.setHorizontalGroup(
            jpYourLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 312, Short.MAX_VALUE)
        );
        jpYourLayout.setVerticalGroup(
            jpYourLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 298, Short.MAX_VALUE)
        );

        jPligaçao.setBorder(javax.swing.BorderFactory.createTitledBorder("Ligaçao"));
        jPligaçao.setEnabled(false);

        jRCliente.setText("Servidor");

        jRServidor.setText("Cliente");

        jTIP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTIPActionPerformed(evt);
            }
        });

        jBLigar.setText("Ligar!");
        jBLigar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBLigarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPligaçaoLayout = new javax.swing.GroupLayout(jPligaçao);
        jPligaçao.setLayout(jPligaçaoLayout);
        jPligaçaoLayout.setHorizontalGroup(
            jPligaçaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPligaçaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPligaçaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPligaçaoLayout.createSequentialGroup()
                        .addComponent(jTIP, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPligaçaoLayout.createSequentialGroup()
                        .addGroup(jPligaçaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jBLigar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jRCliente, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jRServidor)
                        .addGap(75, 75, 75))))
        );
        jPligaçaoLayout.setVerticalGroup(
            jPligaçaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPligaçaoLayout.createSequentialGroup()
                .addComponent(jTIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPligaçaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRCliente)
                    .addComponent(jRServidor))
                .addGap(18, 18, 18)
                .addComponent(jBLigar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jMenu1.setText("Opções");

        jMenuItem6.setText("Jogar já");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem6);

        jMenuItem3.setText("Novo Jogo...");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMnovojogoActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        JMContinuarJogo.setText("Continuar Jogo anterior");
        JMContinuarJogo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JMContinuarJogoActionPerformed(evt);
            }
        });
        jMenu1.add(JMContinuarJogo);

        jMGuardar.setText("Guardar");
        jMGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMGuardarActionPerformed(evt);
            }
        });
        jMenu1.add(jMGuardar);

        jMSair.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMSair.setText("Sair");
        jMSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMSairActionPerformed(evt);
            }
        });
        jMenu1.add(jMSair);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPPlayer, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jladdNomePlayer, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jpMy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPbarcos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(35, 35, 35)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jpYour, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPligaçao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(28, 28, 28)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(182, 182, 182)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPPlayer, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jladdNomePlayer, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(385, 385, 385)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jpMy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jpYour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPligaçao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPbarcos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2)))
                        .addGap(159, 159, 159))))
        );

        jladdNomePlayer.getAccessibleContext().setAccessibleName("lbNamePlayer");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMGuardarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMGuardarActionPerformed

    private void jMSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMSairActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMSairActionPerformed

    private void jMnovojogoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMnovojogoActionPerformed

        this.setEnabled(false);
   
    }//GEN-LAST:event_jMnovojogoActionPerformed
    
    private void JMContinuarJogoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JMContinuarJogoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_JMContinuarJogoActionPerformed

    private void jTIPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTIPActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTIPActionPerformed

    private void jBLigarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBLigarActionPerformed
      
        if (jRCliente.isSelected() == true){
            
            try {
                Server server = new Server();
                server.runServer();
                
            } catch (UnknownError ex) {
                ex.printStackTrace();
            }
            
        }
        else if(jRServidor.isSelected() == true){
            
            try {
                Client cl = new Client("localhost");
             
                        
               
            } catch (UnknownError uHE){
                uHE.printStackTrace();
            }
        }

    }//GEN-LAST:event_jBLigarActionPerformed

    private void jBOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBOkActionPerformed
        IP.setNamePlayer(this.jTnome.getText());
        this.jladdNomePlayer.setText(this.game.getPlayerList().get(0).getName());
    }//GEN-LAST:event_jBOkActionPerformed

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
        if (this.game != null || !this.game.isFull()){
            this.game.addPalyer(new ComputerPlayer());
            this.game.addPalyer(new HumanPlayer("Player XPTO"));
        }
    }//GEN-LAST:event_jMenuItem6ActionPerformed

    public void saveGame() throws IOException {
        JFileChooser guardarFicheiro = new JFileChooser();
        FileFilter filtro = new FileFilter() {
            
            @Override
            public boolean accept(File ficheiro) {
                String nomeFicheiro = ficheiro.getName();
                return nomeFicheiro.endsWith(".txt");
            }
            
            @Override
            public String getDescription() {
                return ".txt";
            }
        };
        
        guardarFicheiro.setFileFilter(filtro);
        int valorReturnado = guardarFicheiro.showSaveDialog(this);
        
        if (valorReturnado == JFileChooser.APPROVE_OPTION) {
            File ficheiro = guardarFicheiro.getSelectedFile();
            System.err.println(ficheiro.getAbsolutePath());
            try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(ficheiro)))) {
            
                oos.writeObject(game);
                oos.flush();
            
            } catch(FileNotFoundException ex) {
                System.err.println("Ficheiro não encontrado!" + ex.getMessage());
            } catch(IOException ex) {
                System.err.println("Não foi possível guardar!" + ex.getMessage());
            }
        }
    }
    
    public void openGame() throws IOException{
                JFileChooser abrirFicheiro = new JFileChooser();
        FileFilter filtro = new FileFilter() {

            @Override
            public boolean accept(File ficheiro) {
                String nomeFicheiro = ficheiro.getName();
                return nomeFicheiro.endsWith(".txt");
            }
            
            @Override
            public String getDescription() {
                return ".txt";
            }
        };
        
        abrirFicheiro.setFileFilter(filtro);
        int valorReturnado = abrirFicheiro.showOpenDialog(this);
        
        if (valorReturnado == JFileChooser.APPROVE_OPTION) {
            File ficheiro = abrirFicheiro.getSelectedFile();
            
            ObjectInputStream ois = null;
        
            try {
                ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(ficheiro)));
                game = (Game) ois.readObject();
                
                System.err.println("Jogo aberto com sucesso!");
            } catch (FileNotFoundException ex) {
                System.err.println("Ficheiro não encontrado!" + ex.getMessage());
            } catch (IOException ex) {
                System.err.println("Não foi possível abrir o ficheiro!" + ex.getMessage());
            } catch (ClassNotFoundException ex) {
                System.err.println( ex.getMessage());
            } finally {
                if (ois != null) {
                 ois.close();
                }
            }
            
            //this.abrirTabuleiro();
        }
        else
            JOptionPane.showMessageDialog(null,"Cancelado pelo jogador","Evento",javax.swing.JOptionPane.INFORMATION_MESSAGE);
    }
   
    private void paintBoard(JPanel panel, JButton jb[][],boolean isOwnBoard){
        panel.setLayout(new GridLayout(10,10));
        
        for(int i=0;i<10;i++)
        {
            for(int j=0;j<10;j++)
            {
                jb[i][j] = new BattleShipJButton(i,j);
                jb[i][j].setBackground( isOwnBoard ? Color.BLUE : Color.GRAY);
                jb[i][j].setPreferredSize(new Dimension(25, 25));
                //sgdfgsdf
                jb[i][j].addActionListener(new ActionListener(){
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        buttonActionPerformed(evt);
                    }
                });
                panel.add(jb[i][j]);
            }
        }
    }
    
    /*private void refreshBoard(JButton jb[][],boolean isOwnBoard){
        
        /*for(int i=0;i<this.game.getPlayerList().get(0).getBoard().getShips().get(0).getSize();i++)
        {
                     jb[this.game.getPlayerList().get(0).getBoard().getShips().get(0).getPoints().get(i).getX()][this.game.getPlayerList().get(0).getBoard().getShips().get(0).getPoints().get(i).getY()].setBackground(Color.RED);

        }
        
        
    }*/
    
     public void buttonActionPerformed(ActionEvent e) {
        BattleShipJButton button = (BattleShipJButton) e.getSource();
        button.setBackground(Color.RED);
        BattleShipJButton[][] battleshipbutton = new BattleShipJButton[Mybt.length][Mybt.length];
        for (int i = 0; i < Mybt.length; i++){
            for (int j = 0; j < Mybt.length; j++){
                battleshipbutton[i][j] = (BattleShipJButton) Mybt[i][j];
            }
        }
        HashMap<Integer,Integer> result;
        result = DetectShapes(battleshipbutton);
        for(Integer i : result.keySet()){
            if ( i > 5 && result.get(i)>=1 || i > 4 && result.get(i)>1 || i > 3 && result.get(i)>2 || i > 2 && result.get(i)>3 ||i > 1 && result.get(i)>4 )
            {
              this.paintBoard(jpMy, Mybt, true);
            }
            JOptionPane.showMessageDialog(null, String.format("%d:%d", i, result.get(i)));
        }
        
        //refreshBoard(Mybt,true);
    }
     
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        //JOptionPane 

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UserInterface().setVisible(true);
                
            }
        });
    }
    
    public HashMap<Integer,Integer> DetectShapes(BattleShipJButton[][] board){
        int size = board.length;

        Tree<BattleShipJButton> tree;
        tree = new Tree<>(null);
        for(int i=0; i < size; i++){
           for(int j= 0; j < size; j++){
                if (board[i][j].getBackground() == Color.RED && 
                        !board[i][j].isAlreadyVisited()){
                    board[i][j].setAlreadyVisited();
                    Node<BattleShipJButton> node = new Node<>();
                    node.setData(board[i][j]);
                    tree.getRoot().addChildren(node);
                    buildTree(board,node,i,j,size);
                }
            }
        }
        HashMap<Integer,Integer> result;
        result = new HashMap<>();
        for(Node<BattleShipJButton> node : tree.getRoot().getChildren()){
             Integer level = getShapeLevel(node);
             result.put(level,result.get(level) == null ? 1 : result.get(level) + 1 );
        }
        for(int i=0; i < size; i++){
           for(int j= 0; j < size; j++){
               board[i][j].unsetAlreadyVisited();
           }
        }
        return result;
    }



    private Integer getShapeLevel(Node<BattleShipJButton> node) {
        Integer level = 0;
        if (node.getChildren() != null && node.getChildren().size() > 0) {
            level = level + node.getChildren().size();
            for(Node<BattleShipJButton> auxNode : node.getChildren()){
                    level = level + getShapeLevel(auxNode);
            }
            return level;
        }
        return 1;
    }



	private void buildTree(BattleShipJButton[][] board, Node<BattleShipJButton> node, int x, int y, int size) {
            if (x < size - 1 || y < size - 1 ){
                if(x < size - 1){
                    int nextX = x+1;
                    if(board[nextX][y].getBackground() == Color.RED && !board[nextX][y].isAlreadyVisited()){
                        board[nextX][y].setAlreadyVisited();
                        Node<BattleShipJButton> childnode = new Node<>();
                        childnode.setData(board[nextX][y]);
                        node.addChildren(childnode);
                        buildTree(board,childnode, nextX,y,size);
                    }
                }
                if(y < size - 1){
                    int nextY = y+1;
                    if(board[x][nextY].getBackground() == Color.RED && !board[x][nextY].isAlreadyVisited()){
                        board[x][nextY].setAlreadyVisited();
                        Node<BattleShipJButton> childnode = new Node<>();
                        childnode.setData(board[x][nextY]);
                        node.addChildren(childnode);
                        buildTree(board,childnode, x,nextY,size);
                    }
                }
            }
	}

	public class Tree<T> {
	    private Node<T> root;

	    public Node<T> getRoot() {
			return root;
		}

		public void setRoot(Node<T> root) {
			this.root = root;
		}

		public Tree(T rootData) {
	        root = new Node<>();
	        root.setData(rootData);
	        root.setChildren(new ArrayList<Node<T>>());
	    }

	}

	
        public class Node<T> {
        private T data;
        private Node<T> parent;
        private ArrayList<Node<T>> children;

        public Node() {
            this.children = new ArrayList<>();
        }

	        public void setData(T data) {
				this.data = data;
			}
			public T getData() {
				return data;
			}
			public void setParent(Node<T> parent) {
				this.parent = parent;
			}
			public Node<T> getParent() {
				return parent;
			}
			public void setChildren(ArrayList<Node<T>> children) {
				this.children = children;
			}
			public ArrayList<Node<T>> getChildren() {
				return children;
			}
			public void addChildren(Node<T> node) {
				if (node.parent == null){
					node.parent = this;
				}
				children.add(node);
			}
	    }


    /*
    private JPanel statusPanel;
    private JLabel statusLabel;
    */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem JMContinuarJogo;
    private javax.swing.JButton jBLigar;
    private javax.swing.JButton jBOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuItem jMGuardar;
    private javax.swing.JMenuItem jMSair;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JPanel jPPlayer;
    private javax.swing.JPanel jPbarcos;
    private javax.swing.JPanel jPligaçao;
    private javax.swing.JRadioButton jRBarci2canos;
    private javax.swing.JRadioButton jRBarco1cano;
    private javax.swing.JRadioButton jRBarco3canos;
    private javax.swing.JRadioButton jRCliente;
    private javax.swing.JRadioButton jRPortavioes;
    private javax.swing.JRadioButton jRServidor;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
    private javax.swing.JRadioButton jRsubmarino;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTIP;
    private javax.swing.JTextField jTnome;
    private javax.swing.JLabel jladdNomePlayer;
    private javax.swing.JPanel jpMy;
    private javax.swing.JPanel jpYour;
    private java.awt.PopupMenu popupMenu1;
    // End of variables declaration//GEN-END:variables
}
